package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;

import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.adapter.Menu_Selected;
import com.example.photography.adapter.Menu_Unselected;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.util.Util;
import com.example.photography.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Menu_Activity extends BaseActivity {
    public static boolean hr_change;

    public static List<String> list = new ArrayList<>();//未选择的fragment
    public static List<String> listselect = new ArrayList<>();//选择的fragment
    public static boolean editsign = false;//true：编辑模式 false：不可编辑模式

    private static Menu_Selected menu_selected;
    private static Menu_Unselected menu_unselected;
    public static List<String> stringList = new ArrayList<>();//原始数据
    @BindView(R.id.tv_edit)
    TextView tvEdit;
    @BindView(R.id.gv_selected)
    GridView gvSelected;
    @BindView(R.id.gv_unselected)
    GridView gvUnselected;
    private String message;
    private StringBuilder hr_sign;


    @Override
    protected void initData() {
        initlist();
        initListen();
        menu_selected = new Menu_Selected(listselect, this);
        menu_unselected = new Menu_Unselected(list, this);
        gvSelected.setAdapter(menu_selected);
        gvUnselected.setAdapter(menu_unselected);

    }

    private void initListen() {
        tvEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (editsign) {//目前可编辑
                    editsign = false;
                    refresh();
                    tvEdit.setText("编辑");
                    hr_change = !equalList(stringList, listselect);
                    if (hr_change) {//数据发生变化
                        sendOKHttp();

                    } else {//数据没变化
                        Util.show(Menu_Activity.this, "数据没变化");
                    }
                } else {
                    editsign = true;
                    refresh();
                    tvEdit.setText("完成");
                }
            }
        });
    }

    private void sendOKHttp() {
        //开启等待动画
        LoadingDialog.getInstance(this).show();

        OkHttpClient client = new OkHttpClient();
        /**
         * String和StringBuilder的区别
         * String
         * 本身不可变，每一次内容发生变化，都会生成一个新的对象，然后原有对象引用新的对象。
         * 每一次生成新对象都会对系统性能产生影响，这会降低.NET编译器的工作效率。
         * StringBuilder
         * 每次操作都是对自身对象进行操作，而不是生成新的对象，其所占空间会随着内容的增加而扩充
         * 在做大量的修改操作时，不会因生成大量匿名对象而影响系统性能
         */
        hr_sign = new StringBuilder();
        for (String temp : listselect) {
            if (hr_sign.length() == 0) {
                hr_sign = new StringBuilder(temp);
            } else {
                hr_sign.append(",").append(temp);
            }
        }

        //POST请求
        FormBody formBody = new FormBody.Builder()
                .add("id_unique", Constant.UID)
                .add("hr_sign", String.valueOf(hr_sign))
                .build();
        Request request = new Request.Builder()
                .url(AppNetConfig.hrsign_change)
                .post(formBody)                //默认就是GET请求就可以不写，这里是post
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                message = "后台君好像生病了~";
                mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonString = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    String status = jsonObject.getString("status");
                    message = jsonObject.getString("msg");
                    if (status.equals("204")) {
                        mHandler.sendEmptyMessageDelayed(2, 0);//关闭等待动画，0延时
                    } else if (status.equals("400")) {
                        message = "请求参数丢失";
                        mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                    } else {
                        message = "未知错误";
                        mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                    }
                } catch (JSONException e) {
                    message = e.toString();
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://修改失败
                    LoadingDialog.getInstance(Menu_Activity.this).dismiss();
                    Util.showToast(Menu_Activity.this, message);
                    break;
                case 2://修改成功
                    LoadingDialog.getInstance(Menu_Activity.this).dismiss();
                    Util.showToast(getApplicationContext(), "修改成功...");
                    //更新数据库
                    Model.getInstance().getDbManger().getUserInfoDao().update_hrsign(Constant.UID, String.valueOf(hr_sign));
                    // TODO: 2020/10/18 传数据失败
//                    Intent intent = new Intent();
//                    intent.putExtra("hr_signarr_select", listselect.toArray(new String[listselect.size()]));//目前现在的数据
//                    intent.putExtra("hr_change",hr_change);
                    removeCurrentActivity();
                    break;

            }
        }
    };

    private void initlist() {
        list.clear();
        listselect.clear();
        stringList.clear();
//        list.add("城市");
//        list.add("黑白");
//        list.add("美食");
//        list.add("情绪");
//        list.add("求点评");
        list.add("人像");
//        list.add("纪实");
        list.add("风光");
        String hr_sign = Model.getInstance().getDbManger().getUserInfoDao().getUserInfo(Constant.UID).getHr_sign();
        if (!hr_sign.equals("")) {
            stringList.addAll(Arrays.asList(hr_sign.split(",")));
            listselect.addAll(stringList);
        }


        for (String temp : listselect) {
            if (list.contains(temp)) {
                list.remove(temp);
            }
        }
    }

    // TODO: 2020/10/14 以后试试能不能不用static
    public static void refresh() {
        menu_selected.notifyDataSetChanged();
        menu_unselected.notifyDataSetChanged();
    }

    private boolean equalList(List list1, List list2) {
        if (list1.size() != list2.size()) {
            return false;
        }
        for (Object object : list1) {
            if (!list2.contains(object)) {
                return false;
            }
        }
        return true;

    }

    @Override
    protected int getLayoutId() {
        return R.layout.menu_activity;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /**
         * static定义的是静态变量，静态变量是整个应用程序的
         * 静态变量是属全局变量、静态变量是整个应用程序的公共变量
         * Activity消毁时，静态变量是不会清除的
         * 只有当各个应用程序的进程消毁时，静态变量才会毁
         * 清除方式:Android.os.Process.killProcess(android.os.Process.myPid());把线程干掉
         */
//        因为HomeFragment要调用数据，所以我放到初始化之前删除数据
//        list.clear();
//        listselect.clear();
//        stringList.clear();
        Log.e("----------", "Menu_Activity destory");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
